package com.tarena.demo.luban.gateway.handler;

import com.tarena.demo.luban.gateway.exception.GatewayException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@Order(-1)
public class MyErrorHandler implements ErrorWebExceptionHandler {
    /**
     * 处理异常
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        //判断抛出的异常是不是GatewayException，如果是，就返回自定义的错误信息，
        // 如果不是，即系统异常，则提示查看日志
        String message;
        if (ex instanceof GatewayException){
            message = ((GatewayException) ex).getMsg();
        } else {
            log.error("系统异常：", ex);
            message = "系统异常，请查看日志";
        }
        ServerHttpResponse response = exchange.getResponse();
        byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
        return response.writeWith(Mono.fromSupplier(() -> response.bufferFactory().wrap(messageBytes)));
    }
}
